package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {

	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public final static String WEB_ROOT  = "c:\\test\\";
	
	
	public Processor(Socket socket) {
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	public void run() {
		String filename = parse(in);
		
		sendFile(filename);
	}
	
	private String parse(InputStream in) {
		String filename = "";
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		try {
			String message = br.readLine();
			if (message == null) {
				return filename;
			}
			String[] messages = message.split(" ");
			
			if (messages.length != 3) {
				sendErrorMessage(400, "client query error!");
				return filename;
			}
			
			System.out.println(messages[0] + "---" +messages[1] + "---" + messages[2]);
			
			filename = messages[1];
		
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		return filename;
	}
	
	public void sendErrorMessage(int errorcode, String errorMessage) {
		out.println("HTTP/1.0 " + errorcode + " " + errorMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");

		out.println("<title>Error Message");
		out.println("</title>");
		
		out.println("<body>");
		
		out.println("</body>");
		out.println("<h1>ErrorCode:" + errorcode + ", errorMessage:"+ errorMessage+"</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	public void sendFile(String filename) {
		if (filename.equals("")) {

			return;
		}
		File file = new File(Processor.WEB_ROOT + filename);
		if (!file.exists()) {
			sendErrorMessage(404, "File not found!");
			
			return;
		}
		
		try {
			InputStream in = new FileInputStream(file);
			byte content[]  = new byte[(int)file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
	}
}
